package org.devgframwork.platform.support.filters;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

//@Component
//@WebFilter(filterName = "requestWebFilter", urlPatterns = "/*")
public class RequestWebFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
//    response.setHeader("Access-control-Allow-Origin", request.getHeader("Origin"));
//    response.setHeader("Access-Control-Allow-Headers", request.getHeader("Access-Control-Request-Headers"));
        response.setHeader("Access-control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Headers", "*");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.addHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT");
        response.setHeader("Access-Control-Max-Age", "3600");
        String requestMethod = request.getMethod();
        if ("OPTIONS".equals(requestMethod)) {
//      response.setStatus(HttpStatus.NO_CONTENT.value());
            return;
        }
        filterChain.doFilter(servletRequest, servletResponse);
        /*String contentType = servletRequest.getContentType();
        if (null != contentType && contentType.contains("multipart/form-data")) {
            ParameterRequestWrapper httpServletRequestWrapper = new ParameterRequestWrapper((HttpServletRequest) servletRequest);
            Map<String, String[]> parameterMap = httpServletRequestWrapper.getParameterMap();
            *//*parameterMap.put("a", new String[]{"杜恒"});*//*
            httpServletRequestWrapper.setParameterMap(parameterMap);
            filterChain.doFilter(httpServletRequestWrapper, servletResponse);
        } else if (null != contentType && contentType.contains("application/json")) {
            JSONObject jsonObject = RequestBodyParameterWrapper.getInputStr((HttpServletRequest) servletRequest);
            *//*jsonObject.put("a", "杜恒");*//*
            String parameterString = JSONObject.toJSONString(jsonObject);
            RequestBodyParameterWrapper httpServletRequestWrapper = new RequestBodyParameterWrapper((HttpServletRequest) servletRequest, parameterString);
            filterChain.doFilter(httpServletRequestWrapper, servletResponse);
        } else {
            filterChain.doFilter(servletRequest, servletResponse);
        }*/
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void destroy() {

    }
}
